package com.starbaba.module.view;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.struts2.ServletActionContext;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.starbaba.core.download.Request;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.model.utils.JSONUtils;

@SuppressWarnings({"deprecation","unused"})
public class FileUploadAction extends BaseAction {
	
	private static final long serialVersionUID = 572146812454l;
	private static final int BUFFER_SIZE = 16 * 1024;

	// 注意，文件上传时<s:file/>同时与myFile，myFileContentType,myFileFileName绑定
	// 所以同时要提供myFileContentType,myFileFileName的set方法

	private File [] myFile; // 上传文件
    private String contentType;// 上传文件类型
	private String fileName; // 上传文件名
	private String imageFileName;
	private String caption;// 文件说明，与页面属性绑定

	public void setMyFileContentType(String contentType) {
		System.out.println("文件类型 : " + contentType);
		this.contentType = contentType;
	}

	public void setMyFileFileName(String fileName) {
		System.out.println("文件名称 : " + fileName);
		this.fileName = fileName;
	}

	public void setMyFile(File [] myFile) {
		this.myFile = myFile;
	}

	public String getImageFileName() {
		return imageFileName;
	}

	public String getCaption() {
		return caption;
	}

	public void setCaption(String caption) {
		this.caption = caption;
	}

	public static void copy(File src, File dst) {
		try {
			InputStream in = null;
			OutputStream out = null;
			try {
				in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
				out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
				byte[] buffer = new byte[BUFFER_SIZE];
				while (in.read(buffer) > 0) {
					out.write(buffer);
				}
			} finally {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
    
	@SuppressWarnings("resource")
	public String uploadImg2Qiniu(File path) throws ClientProtocolException, IOException {
		
	    String url = "";
        HttpClient httpclient = new DefaultHttpClient();
		// 请求处理页面
		HttpPost httppost = new HttpPost(Constant.COMMON_HOST + "/image_service/upload?funid=2000");
		// 创建待处理的表单域内容文本
		StringBody data = new StringBody("{modules:activity}");

		// 创建待处理的文件
		FileBody file1 = new FileBody(path);

		// 对请求的表单域进行填充
		MultipartEntity reqEntity = new MultipartEntity();
		reqEntity.addPart("data", data);
		reqEntity.addPart("file", file1);
		// reqEntity.addPart("file", file2);
		// 设置请求
		httppost.setEntity(reqEntity);
		// 执行
		HttpResponse response = httpclient.execute(httppost);
		if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
			HttpEntity entity = response.getEntity();
			// 显示内容
			if (entity != null) {
				// {
				//  "imgurl": "user/2017_04/20170401203923_711_149104523512639.png",
				//  "qiniuimgurl": "http://loanimg.moneyfanli.com/user/2017_04/20170401203923_711_149104523512639.png",
				//  "qiniukey": "user/2017_04/20170401203923_711_149104523512639.png"
				// }
				String jsonStr = EntityUtils.toString(entity, "UTF-8");
				JsonObject responseJson = JSONUtils.toJsonObject(jsonStr);
				JsonArray urlArray = responseJson.getAsJsonArray("url");
				if (urlArray != null && urlArray.size() > 0) {
					JsonObject result = urlArray.get(0).getAsJsonObject();
					url = JSONUtils.checkAsString(result, "qiniuimgurl");
				}
			}
		}
		return url;
	}
	
	public static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos);
	}

	public void upload() throws ClientProtocolException, IOException {
		String[] files = fileName.split(",");
		StringBuffer image = new StringBuffer();
		if(files != null && files.length > 0){
			int i = 0;
			for(String file : files){
				imageFileName = new Date().getTime() + getExtention(file);
		 		File imageFile = new File(ServletActionContext.getServletContext().getRealPath("UploadImages") + "/" + imageFileName);
		 		if(!imageFile.getParentFile().exists()){
                    imageFile.getParentFile().mkdirs();
                }
		 		copy(myFile[i], imageFile);
				String imageOr = uploadImg2Qiniu(imageFile);
				System.out.println(imageOr);
				if(i > 0){
					image.append("#");
				}
				image.append(imageOr);
				i = i + 1;
			}
			System.out.println(image);
		}
		sendJsonMessage(JsonUtils.toJson(image, null, true, null, false));
	}
}